<template>
  <div>
    <el-container>
      <el-header>
        <h2>
          <b>角色管理</b>
        </h2>
      </el-header>
      <el-main>
        <el-form :inline="true" :model="role" ref="role" class="demo-form-inline" align="center">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="role.name" placeholder="角色名"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="permsId">
            <el-cascader
              :options="options"
              :props="props"
              collapse-tags
              clearable
              v-model="role.permsId"
              placeholder="请选择权限"
              style="width:250px"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="role.status" placeholder="请选择状态">
              <el-option label="全部" value="0"></el-option>
              <el-option label="正常" value="y"></el-option>
              <el-option label="冻结" value="n"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="page=1;onSubmit()">查询</el-button>
            <el-button @click="resetForm('role')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="tData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="序号" type="index" width="50"></el-table-column>
          <el-table-column prop="name" label="名称" width="200"></el-table-column>
          <el-table-column prop="description" label="描述" width="600"></el-table-column>
          <el-table-column prop="status" label="状态" width="150" :formatter="formatStatus"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="view(scope.row)" type="primary" size="mini">权限</el-button>
              <el-button
                @click="handleClick(scope.row)"
                type="primary"
                size="mini"
                v-if="scope.row.id!=1"
              >编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalNum"
          :page-size="3"
          align="center"
          :current-page="page"
          @current-change="handleCurrentChange"
        ></el-pagination>
        <br />
        <div align="center">
          <el-button type="primary" @click="dialogFormVisibleAdd=true">增加</el-button>
          <!-- <el-button type="primary" @click="delAll">批量删除</el-button> -->
        </div>
      </el-main>
    </el-container>

    <el-dialog
      title="角色添加"
      :visible.sync="dialogFormVisibleAdd"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form :model="form" ref="form" :rules="formrules">
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth" prop="permsId">
          <el-tree v-model="form.permsId" :data="data" ref="tree" show-checkbox node-key="id"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose('form','tree')">取 消</el-button>
        <el-button type="primary" @click="add('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="角色信息"
      :visible.sync="dialogFormVisibleView"
      :modal="false"
      :close-on-click-modal="false"
    >
      <el-table :data="rolePerm" border style="width: 100%">
        <el-table-column prop="name" label="课程名"></el-table-column>
        <el-table-column prop="identity" label="标识"></el-table-column>
        <el-table-column prop="link" label="链接"></el-table-column>
        <el-table-column prop="pId" label="父权限" :formatter="formatPId"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      title="角色修改"
      :visible.sync="dialogFormVisibleUpdate"
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form :model="updateform" ref="updateform" :rules="formrules">
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="updateform.name"></el-input>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth" prop="description">
          <el-input type="textarea" v-model="updateform.description"></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth" prop="permsId">
          <el-tree
            v-model="updateform.permsId"
            :data="data"
            ref="treeUpd"
            show-checkbox
            node-key="id"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClose('updateform','treeUpd')">取 消</el-button>
        <el-button type="primary" @click="update('updateform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Axios from "axios";
import Qs from "qs";
export default {
  data() {
    var validateRePwd = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      role: {
        name: "",
        permsId: "",
        status: "",
      },
      form: {
        name: "",
        description: "",
        permsId: "",
      },
      updateform: {
        id: "",
        name: "",
        description: "",
        permsId: "",
      },
      formrules: {
        name: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { max: 10, message: "最多10个字符", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { max: 50, message: "最多50个字符", trigger: "blur" },
        ],
      },
      perms: [],
      tData: [],
      rolePerm: [],
      multipleSelection: [],
      totalNum: 0,
      page: 1,
      dialogFormVisibleAdd: false,
      dialogFormVisibleUpdate: false,
      dialogFormVisibleView: false,
      formLabelWidth: "120px",
      props: { multiple: true },
      options: [],
    };
  },
  created() {
    Axios.get("/tfss/admin/perm/list").then((r) => {
      if (r.data.code == 200) {
        this.perms = r.data.data;
        for (const perm1 of this.perms) {
          let father = {
            value: "",
            label: "",
            children: [],
          };
          if (perm1.pid == null) {
            father.value = perm1.id;
            father.label = perm1.name;
            for (const perm2 of this.perms) {
              let child = {
                value: "",
                label: "",
              };
              if (perm2.pid == perm1.id) {
                child.value = perm2.id;
                child.label = perm2.name;
                father.children.push(child);
              }
            }
            this.options.push(father);
          }
        }
        for (const perm1 of this.perms) {
          let father = {
            id: "",
            label: "",
            children: [],
          };
          if (perm1.pid == null) {
            father.id = perm1.id;
            father.label = perm1.name;
            if (perm1.id == 1 || perm1.id == 4) {
              father.disabled = true;
            }
            for (const perm2 of this.perms) {
              let child = {
                id: "",
                label: "",
              };
              if (perm2.pid == perm1.id) {
                child.id = perm2.id;
                if(perm2.type=="m"){
                  child.label = perm2.name+"（菜单）";
                }else{
                  child.label = perm2.name;
                }
                if (perm2.pid == 1 || perm2.pid == 4) {
                  child.disabled = true;
                }
                father.children.push(child);
              }
            }
            this.data.push(father);
          }
        }
        this.onSubmit();
      } else if (r.data.code == 403) {
        this.$message.error("没有权限");
      } else if (r.data.code == 703) {
        this.$message.error("未登录");
      } else if (r.data.code == 500) {
        this.$message.error("系统繁忙，请稍后再试");
      } else if (r.data.code == 704) {
        this.$message.error("登录失效，请重新登录");
      }
    });
  },
  methods: {
    onSubmit() {
      let result = [];
      let data = this.role.permsId;
      for (const i of data) {
        for (const j of i) {
          let b = true;
          for (const r of result) {
            if (r == j) {
              b = false;
              break;
            }
          }
          if (b == true) {
            result.push(j);
          }
        }
      }
      Axios.get("/tfss/admin/role/listByPage", {
        params: {
          name: this.role.name,
          permsId: result,
          status: this.role.status,
          page: this.page,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onClose(formName, treeName) {
      this.$refs[formName].resetFields();
      this.$refs[treeName].setCheckedKeys([]);
      this.dialogFormVisibleAdd = false;
      this.dialogFormVisibleUpdate = false;
    },
    add(formName) {
      this.form.permsId = this.$refs.tree.getCheckedKeys();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认增加?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Axios.post(
                "/tfss/admin/role/add",
                Qs.stringify(this.form, { indices: false })
              ).then((r) => {
                if (r.data.code === 200) {
                  this.$message({
                    type: "success",
                    message: "增加成功!",
                  });
                  this.dialogFormVisibleAdd = false;
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                } else if (r.data.code == 706) {
                  this.$message.error("角色名已存在");
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    view(row) {
      Axios.get("/tfss/admin/role/view", {
        params: {
          id: row.id,
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.rolePerm = r.data.data;
          this.dialogFormVisibleView = true;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    update(formName) {
      this.updateform.permsId = this.$refs.treeUpd.getCheckedKeys();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确认修改?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Axios.post(
                "/tfss/admin/role/update",
                Qs.stringify(this.updateform, { indices: false })
              ).then((r) => {
                if (r.data.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                  });
                  this.dialogFormVisibleUpdate = false;
                  this.onSubmit();
                } else if (r.data.code == 403) {
                  this.$message.error("没有权限");
                } else if (r.data.code == 703) {
                  this.$message.error("未登录");
                } else if (r.data.code == 500) {
                  this.$message.error("系统繁忙，请稍后再试");
                } else if (r.data.code == 704) {
                  this.$message.error("登录失效，请重新登录");
                } else if (r.data.code == 705) {
                  this.$message.error("账号已存在");
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消",
              });
            });
        } else {
          return false;
        }
      });
    },
    handleClick(row) {
      this.updateform = JSON.parse(JSON.stringify(row));
      this.dialogFormVisibleUpdate = true;
      Axios.get("/tfss/admin/role/view", {
        params: {
          id: row.id,
        },
      }).then((r) => {
        if (r.data.code == 200) {
          if (r.data.data != null && r.data.data != "") {
            let result = [];
            for (const perm of r.data.data) {
              if (perm.pid != null && perm.pid != 0) {
                result.push(perm.id);
              }
            }
            this.$refs.treeUpd.setCheckedKeys(result);
          }
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
    formatStatus(row, column, cellValue) {
      return "正常";
    },
    formatPId(row, column, cellValue) {
      if (cellValue == null || cellValue == "") {
        return "主菜单";
      }
      for (const perm of this.perms) {
        if (cellValue == perm.id) {
          return perm.name;
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      let result = [];
      let data = this.role.permsId;
      for (const i of data) {
        for (const j of i) {
          let b = true;
          for (const r of result) {
            if (r == j) {
              b = false;
              break;
            }
          }
          if (b == true) {
            result.push(j);
          }
        }
      }
      Axios.get("/tfss/admin/role/listByPage", {
        params: {
          name: this.role.name,
          permsId: result,
          status: this.role.status,
          page: val,
        },
        paramsSerializer: (params) => {
          return Qs.stringify(params, { indices: false });
        },
      }).then((r) => {
        if (r.data.code == 200) {
          this.tData = r.data.data.records;
          this.totalNum = r.data.data.total;
          this.page = val;
        } else if (r.data.code == 403) {
          this.$message.error("没有权限");
        } else if (r.data.code == 703) {
          this.$message.error("未登录");
        } else if (r.data.code == 500) {
          this.$message.error("系统繁忙，请稍后再试");
        } else if (r.data.code == 704) {
          this.$message.error("登录失效，请重新登录");
        }
      });
    },
  },
};
</script>

<style scoped>
.el-header,
.el-footer {
  /* background-color: #b3c0d1; */
  color: #333;
  /* text-align: center; */
  line-height: 60px;
}
.el-main {
  /* background-color: #e9eef3; */
  color: #333;
  /* text-align: center; */
  /* line-height: 160px; */
}
</style>